package fr.controller;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import fr.business.ManageApplicationsBusinessService;
import fr.form.synthese.SyntheseEcranApplications;
import fr.form.synthese.SyntheseEcranParticipation;
import fr.utilities.Constantes;

@Controller
@RequestMapping("/user")
public class ManageUserApplicationsController {

	@Autowired
	private ManageApplicationsBusinessService bs;

	@RequestMapping("/showApps")
	public String listApplications(Map<String, Object> map,@ModelAttribute("ApplicationUserForm")
	SyntheseEcranApplications ecran) {
		map.put("listApplication", bs.getStartedApplications());
		return "user/showApps";
	}

	@ResponseBody
	@RequestMapping(value="/participer",method=RequestMethod.POST)
	public String participer(@RequestParam(value="id") Integer id){
		if(bs.participerAction(Constantes.USER, id)){
			return "success";
		}
		return "error";
	}
	
	
	@RequestMapping(value="/validParticipation",method=RequestMethod.POST)
	public String validParticipation(Map<String, Object> map,
				@ModelAttribute("ApplicationUserForm") SyntheseEcranApplications ecranApp,
				@ModelAttribute("ValidationParticipationForm") SyntheseEcranParticipation ecranPart){

		bs.prepareDate(ecranPart.getIdApp(),map);
		
		ecranPart.setIdApp(ecranApp.getIdApp());
		
		return "user/participation";
	}
	
	@RequestMapping(value="/validParticipationOk",method=RequestMethod.POST)
	public String validParticipationOk(Map<String, Object> map,
				@Valid @ModelAttribute("ValidationParticipationForm") SyntheseEcranParticipation ecranPart,
				BindingResult result){

		if(result.hasFieldErrors()){
			
			bs.prepareDate(ecranPart.getIdApp(),map);
			
			return "user/participation";

		}else{
			bs.validerParticiperAction(Constantes.USER, ecranPart.getIdApp(),ecranPart);
			return "redirect:/user/showApps";
		}
	}

}
